from django.contrib import admin

# Register your models here.
from django.contrib.sites.models import Site
from django.urls import reverse
from django.utils.html import format_html

from reports.models import CaseResult, SuitReport, StepResult


class ReadOnlyModelAdmin(admin.ModelAdmin):
    """ModelAdmin class that prevents modifications through the admin.

    The changelist and the detail view work, but a 403 is returned
    if one actually tries to edit an object.
    """

    actions = None

    def get_readonly_fields(self, request, obj=None):
        return self.fields or [f.name for f in self.model._meta.fields]

    def has_add_permission(self, request):
        return False

    # Allow viewing objects but not actually changing them
    def has_change_permission(self, request, obj=None):
        return False

    def has_delete_permission(self, request, obj=None):
        return False


class ReadOnlyTabularInline(admin.TabularInline):
    """ModelAdmin class that prevents modifications through the admin.

    The changelist and the detail view work, but a 403 is returned
    if one actually tries to edit an object.
    """

    def has_change_permission(self, request, obj=None):
        return False

    def has_add_permission(self, request, obj=None):
        return False

    def has_delete_permission(self, request, obj=None):
        return False

class CaseResultInline(ReadOnlyTabularInline):

    model = CaseResult
    fk_name = "case_result_suit"
    show_change_link = True



class StepResultInline(ReadOnlyTabularInline):

    model = StepResult
    fk_name = "case_result"
    fieldsets = [(None, {'fields': ['step_description','operation_type', 'result_status']})
                 ]
    # list_display_links = ('result_status',)
    show_change_link = True



# class BInline(admin.StackedInline):
#     model = CaseResult

@admin.register(SuitReport)
class SuitReportAdmin(ReadOnlyModelAdmin):
    inlines = [CaseResultInline]
    # listdisplay设置要显示在列表中的字段（id字段是Django模型的默认主键）
    list_display = ('id', 'test_suit','start_time','end_time','take_time','total_count','pass_rate','created_time','link_to_case_result')
    # list_per_page设置每页显示多少条记录，默认是100条
    list_per_page = 50

    # ordering设置默认排序字段，负号表示降序排序
    ordering = ('-created_time',)

    # list_editable 设置默认可编辑字段
    # list_editable = ['address', 'ip']

    # fk_fields 设置显示外键字段
    fk_fields = ('test_suit',)

    # def link_to_case_result(self, obj):
    #     # info = (obj.category._meta.app_label, obj.category._meta.model_name)
    #     # link = reverse('admin:%s_%s_change' % info, args=(obj.category.id,))
    #     site=Site.objects.get_current().domain
    #     url = "http://{site}/admin/reports/caseresult/?case_result_suit__basemodel_ptr__exact={path}".format(site=site, path=obj.id)
    #     return format_html(u'<a href="%s">查看</a>' % (url,))
    #
    # link_to_case_result.short_description = '结果明细'
    # link_to_case_result.allow_tags = True


    def link_to_case_result(self, obj):
        # info = (obj.category._meta.app_label, obj.category._meta.model_name)
        # link = reverse('admin:%s_%s_change' % info, args=(obj.category.id,))
        site=Site.objects.get_current().domain
        url = "http://{site}/report/detail/{id}.html".format(site=site, id=obj.id)
        return format_html(u'<a href="%s">查看</a>' % (url,))

    link_to_case_result.short_description = '结果明细'
    link_to_case_result.allow_tags = True






@admin.register(CaseResult)
class CaseResultAdmin(ReadOnlyModelAdmin):
    inlines = [StepResultInline]
    # listdisplay设置要显示在列表中的字段（id字段是Django模型的默认主键）
    list_display = ('id','test_case', 'case_result_suit','start_time','end_time','take_time','result_status_color','created_time')

    # list_per_page设置每页显示多少条记录，默认是100条
    list_per_page = 50

    # ordering设置默认排序字段，负号表示降序排序
    ordering = ('-created_time',)

    list_filter = ('case_result_suit',)

    # list_editable 设置默认可编辑字段
    # list_editable = ['address', 'ip']

    # fk_fields 设置显示外键字段
    fk_fields = ('id',)
    def result_status_color(self , obj):
        if obj.result_status == 'pass':
            return format_html('<span style="color:green">{}</span>','成功')
        else:
            return format_html('<span style="color:red">{}</span>','失败')
    result_status_color.short_description = "结果"
    fieldsets = (("概览", {'fields': ('test_case', ('result_status', 'take_time'),('start_time','end_time'))}),
                 ('日志', {'classes': ('collapse', 'extrapretty'),  # 'collapse','wide', 'extrapretty'
                     'fields': ('log_text',)
                 }),
    )




@admin.register(StepResult)
class StepResultAdmin(ReadOnlyModelAdmin):
    # listdisplay设置要显示在列表中的字段（id字段是Django模型的默认主键）
    list_display = ('id', 'test_step','assert_result','result_status_color','created_time')

    # list_per_page设置每页显示多少条记录，默认是100条
    list_per_page = 50

    # ordering设置默认排序字段，负号表示降序排序
    ordering = ('-created_time',)

    list_filter = ('test_step',)

    # list_editable 设置默认可编辑字段
    # list_editable = ['address', 'ip']

    # fk_fields 设置显示外键字段
    fk_fields = ('id',)
    # search_fields = ['case_result_suit_','result_status']
    def result_status_color(self , obj):
        if obj.result_status == 'pass':
            return format_html('<span style="color:green">{}</span>','成功')
        else:
            return format_html('<span style="color:red">{}</span>','失败')
    result_status_color.short_description = "结果"



